package net.http
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLStream;
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	
	/**
	 * http请求
	 * @author william
	 * 
	 */ 
	public class RequestController extends EventDispatcher
	{
		private var __stream:URLLoader;
		private var __request:URLRequest;
		private var __data:Object;
		
		
		//这里是每次发出请求后返回的数据
		public function get data():Object
		{
			return __data;
		}
		
		public function RequestController()
		{
		}
		
		/**
		 * 发出一个http请求 
		 * @param method get | post
		 * @param url 请求url
		 * @param request_params 发送的参数
		 * 
		 */  
		public function request(method:String,url:String,request_params:URLVariables):void
		{
			__stream = new URLLoader();
			__request = new URLRequest(url);
			
			__request.data = request_params;
			__request.method = method;
			__setHeaders(__request);
			
			__stream.addEventListener(Event.COMPLETE, __completeHandler);
			__stream.addEventListener(IOErrorEvent.IO_ERROR, __onIOError);
			
			__stream.load(__request);
		}
		
		private function __onIOError(evt:IOErrorEvent):void
		{
			
			//将异常事件发出，由调用者处理
			dispatchEvent(evt);
			dispose();
		}
		
		/**
		 * 设置头信息(这一块很重要，有的不设置头信息就无法正确请求)
		 * @param request
		 * 
		 */  
		private function __setHeaders(request:URLRequest):void
		{
			//设置头信息
			var accept:URLRequestHeader = new URLRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			var acceptLanguage:URLRequestHeader = new URLRequestHeader("Accept-Language", "zh-cn,zh;q=0.5");
			var contentType:URLRequestHeader = new URLRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request.requestHeaders.push(accept, acceptLanguage, contentType);
		}
		
		/**
		 * 获取数据
		 * @param evt
		 * 
		 */  
		private function __completeHandler(evt:Event):void
		{
			try
			{
				__data = evt.currentTarget.data;
				
				//发出事件，告知调用者可以取数据了
				dispatchEvent(evt);
				dispose();
			}
			catch (err:Error)
			{
				trace("ERROR:" + err.getStackTrace());
			}
		}  
		
		/**
		 * 清空 
		 */  
		public function dispose():void
		{
			IEventDispatcher(__stream).removeEventListener(Event.COMPLETE, __completeHandler);
			IEventDispatcher(__stream).removeEventListener(IOErrorEvent.IO_ERROR, __onIOError);
			__stream = null;
			__request = null;
			__data = null;
		}
	}
}